<template>
    <div class="screen">
      <screenfull id="screenfull" v-show="!loading" class="right-menu-item hover-effect full-btn pointer" />
      <dv-loading v-if="loading" style="color:#fff;;">Loading...</dv-loading>
      <div class="content" v-if="!loading">
        <div class="title">
            <img v-if="logo" :src="logo" class="logo"/>
            <img v-else src="@/assets/screen/logo.png" class="logo"/>
            {{title}}
        </div>
        <div class="role-name pointer" @click="goIndex"><i class="el-icon-arrow-left"></i>工作台</div>
        <div class="time">{{time}}</div>
        <div class="flex">
          <div v-for="item,index in list" :key="index" :class="[index<2?'pointer':'']">
            <item-text :item="item" @itemTextClick="itemTextClick"/>
          </div>
        </div>
        <div class="flex">
          <div class="chart-wrap">
            <item-chart :item="item"  v-for="item,index in list2"  :key="index"/>
          </div>
          <div class="flex-center">
              <item-map :mapData="mapData"/>
              <item-table :tableData="tableData"/>
          </div>
          <div class="chart-wrap">
            <item-chart :item="item"  v-for="item,index in list3"  :key="index"/>
          </div>
        </div>
      </div>
       <el-dialog title="测量数据" :visible.sync="testView" width="80vw" append-to-body>
         <test-table ref="testTable" @closeTestView="closeTestView"/>
       </el-dialog>

    </div>
</template>

<script>
  import screenTitle from "./components/title.vue";
  import nameAndTime from "./components/nameAndTime.vue";
  import itemText from "./components/item-text.vue";
  import itemChart from "./components/item-chart.vue";
  import itemMap from "./components/item-map";
  import itemTable from "./components/item-table";
  import testTable from "./components/test-table";
  import {
  getToken
  } from "@/utils/auth";
  import {
  parseTime
  } from "@/utils/ruoyi";
import {
    patientNumKpiData,
    patientTestActionKpiData,
    doctorTaskKpiData,
    patientAreaScatterCountData,
    patientEvaluateCountData,
    deviceCountData,
    patientAgeCountData,
    patientSexCountData
  } from "@/api/manbing/screen";
  import {
    newestBloodTestList
  } from "@/api/manbing/doctor";
  import Screenfull from "@/components/Screenfull";
  export default {
    name: "Screen",
    components: {
      screenTitle,
      nameAndTime,
      itemText,
      itemChart,
      itemMap,
      itemTable,
      testTable,
      Screenfull
    },
    data() {
      return {
        loading:false,
        roleId: sessionStorage.getItem("roleId"),
        logo:'',
        title:'海权康护血压测量数据大屏',
        time:'',
        weeks:['日','一','二','三','四','五','六'],
        colors:['#409EFF','rgb(253,154,1)','red'],//警告颜色
        list: [{
            title: '患者总数',
            value: 0,
            plus:0,
            unit: '人',
            data: [{
                title: '原发性',
                value: 0,
                plus: 0
              },
              {
                title: '继发性',
                value: 0,
                plus: 0
              },
            ],
          },
          {
            title: '总测量次数',
            value: 0,
            unit: '次',
            plus:0,
            data: [{
                title: '正常',
                value: 0,
                plus: 0
              },
              {
                title: '偏高',
                value: 0,
                plus: 0
              },
              {
                title: '中度',
                value: 0,
                plus: 0
              },
              {
                title: '严重',
                value: 0,
                plus: 0
              },
            ],
          },
          {
            title: '回访总次数',
            value: 0,
            unit: '次',
            plus:0,
            data: [{
                title: '提醒',
                value: 10,
                plus: 1
              },
              {
                title: '关怀',
                value: 10,
                plus: 1
              },
            ]
          },
      ],
        list2:[
          {id:'chart1',title:'预警占比',data:[
            {title:'正常',value:-1,color:'#00FF00'},
            {title:'偏高',value:-1,color:'#409EFF'},
            {title:'中度',value:-1,color:'rgb(253,154,1)'},
            {title:'严重',value:-1,color:'red'},
          ]},
          {id:'chart2',title:'设备绑定',data:[
            {title:'已绑定',value:-1,color:'#00FF00'},
            {title:'未绑定',value:-1,color:'#409EFF'},
          ]},
          {id:'chart3',title:'患者评价',data:[]}
        ],
        list3:[
          {id:'chart4',title:'病类占比',data:[
            {title:'原发性',value:-1,color:'#00FF00'},
            {title:'继发性',value:-1,color:'#409EFF'},
          ]},
          {id:'chart5',title:'年龄占比',data:[]},
          {id:'chart6',title:'性别占比',data:[
            {title:'男',value:-1,color:'#00FF00'},
            {title:'女',value:-1,color:'#409EFF'},
          ]}
        ],
        listTemp:null,
        list2Temp:null,
        list3Temp:null,
        tableDataTemp:null,
        mapDataTemp:null,
        queryParams: {
          pageNum: 1,
          pageSize: 9,
        },
        tableData:[],
        mapData:[],
        testView:false,//测量弹出
        websock:null,
        timer:null,
    };
  },
  watch: {
    $route(to, from) {
      if (to.path.indexOf('/manbing/screen') > -1) {
        setTimeout(()=>{
         this.showLoading()
        },100)

      }
    },
    loading(val){
      if(!val){
          this.refresh()
      }
    }
  },
  created() {
    this.setName()
    this.setTime()
    setInterval(()=>{
        this.setTime()
    },2000)
     this.init()
     this.onresize()
     this.initWebSocket()

    },
    methods: {
      goIndex(){
        this.$router.push({path:'/index'})
      },
      setName(){
        if(sessionStorage.getItem("user")){
          let data=JSON.parse(sessionStorage.getItem("user"))
          if(this.roleId!=2){
           if(data.dept.sysName||data.dept.deptName){
             this.title=data.dept.sysName||data.dept.deptName
           }
           if(data.dept.logoImg){
            this.logo=data.dept.logoImg
           }
          }
        }
      },
      setTime(){
         let now=new Date(),
         month=now.getMonth()+1,
         date=now.getDate(),
         hours=now.getHours(),
         minutes=now.getMinutes();
         this.time=now.getFullYear()+'年'+(month<10?('0'+month):month)
         +'月'+(date<9?('0'+date):date)+'日 周'+this.weeks[now.getDay()]+' '+(hours<10?('0'+hours):hours)+':'+(minutes<10?('0'+minutes):minutes)
      },
      onresize(){
        window.addEventListener('resize',()=>{
          if(this.$route.name=='Screen'){
            this.showLoading()
          }
        })
      },
      showLoading(){
        if(this.timer){
          clearInterval(this.timer)
          this.timer=null
        }
        this.loading = true;
        this.timer=setTimeout(()=>{
          this.loading = false;
        },500)
      },
      refresh(){
        if(this.list){
           this.listTemp=JSON.stringify(this.list)
         }
         if(this.list2){
           this.list2Temp=JSON.stringify(this.list2)
         }
         if(this.list3){
           this.list3Temp=JSON.stringify(this.list3)
         }
         if(this.tableData){
           this.tableDataTemp=JSON.stringify(this.tableData)
         }
         if(this.mapData){
           this.mapDataTemp=JSON.stringify(this.mapData)
         }
        this.$nextTick(()=>{
          if(this.listTemp){
            this.list=JSON.parse(this.listTemp)
          }
          if(this.list2Temp){
            this.list2=JSON.parse(this.list2Temp)
          }
          if(this.list3Temp){
            this.list3=JSON.parse(this.list3Temp)
          }
          if(this.tableDataTemp){
            this.tableData=JSON.parse(this.tableDataTemp)
          }
          if(this.mapDataTemp){
            this.mapData=JSON.parse(this.mapDataTemp)
          }
        })
      },
      init(){
        console.log('--------------------');
        this.getPatientNumKpiData()
        this.getPatientTestActionKpiData()
        this.getDoctorTaskKpiData()
        this.getPatientEvaluateCountData()
        this.getDeviceCountData()
        this.getPatientAgeCountData()
        this.getPatientSexCountData()
        this.getPatientAreaScatterCountData()
        this.getNewestBloodTestList()
      },
      //显示测量数据
      action(index) {
        if(!index){
          this.$router.push('/manbing/patient')
        }else if(index==1){
          this.testView=true
          this.$nextTick(() => {
            this.$refs.testTable.init();
          });
        }
      },
      itemTextClick(data){
        if(data.title=='患者总数'){
          let url=`/manbing/patient`
          if(data.index>-1){
            url+='?index='+data.index
            if(data.today){
              url+='&today=1'
            }
          }else if(data.today){
            url+='?today=1'
          }
           let routeUrl = this.$router.resolve({
                path: url,
              })
              window.open(routeUrl.href, '_blank')
          // this.$router.push(url)
        }else if(data.title=='总测量次数'){
          this.testView=true
          this.$nextTick(() => {
            this.$refs.testTable.init(data);
          });
        }
      },
      closeTestView(){
        this.testView=false
      },
      //患者人数KPI
      getPatientNumKpiData(){
        patientNumKpiData({}).then(res=>{
          if(res.code==200){
              this.list[0].value=res.data.totalNum
              this.list[0].plus=res.data.todayAddNum
              this.list[0].data[0].value=res.data.totalEssentialNum
              this.list[0].data[0].plus=res.data.todayAddEssentialNum
              this.list[0].data[1].value=res.data.totalSecondaryNum
              this.list[0].data[1].plus=res.data.todayAddSecondaryNum

              this.list3[0].data[0].value=res.data.totalEssentialNum
              this.list3[0].data[1].value=res.data.totalSecondaryNum
          }
        })
      },
    //患者测量行为指标KPI
      getPatientTestActionKpiData(){
        patientTestActionKpiData({}).then(res=>{
          if(res.code==200){
              this.list[1].value=res.data.totalNum
              this.list[1].plus=res.data.todayAddNum
              this.list[1].data[0].value=res.data.totalNormalNum
              this.list[1].data[0].plus=res.data.todayAddNormalNum
              this.list[1].data[1].value=res.data.totalGeneralAlarmNum
              this.list[1].data[1].plus=res.data.todayAddGeneralAlarmNum
              this.list[1].data[2].value=res.data.totalModeratelAlarmNum
              this.list[1].data[2].plus=res.data.todayAddModeratelAlarmNum
              this.list[1].data[3].value=res.data.totalSeriousAlarmNum
              this.list[1].data[3].plus=res.data.todayAddSeriousAlarmNum


                  this.list2[0].data[0].value=res.data.totalNormalNum
                  this.list2[0].data[1].value=res.data.totalGeneralAlarmNum
                  this.list2[0].data[2].value=res.data.totalModeratelAlarmNum
                  this.list2[0].data[3].value=res.data.totalSeriousAlarmNum
          }
        })
      },
    //医生任务指标KPI
      getDoctorTaskKpiData(){
        doctorTaskKpiData({}).then(res=>{
          if(res.code==200){
            this.list[2].value=res.data.totalRemindNum+res.data.totalCaredNum
            this.list[2].plus=res.data.todayAddRemindNum+res.data.todayAddCaredNum

              this.list[2].data[0].value=res.data.totalRemindNum
              this.list[2].data[0].plus=res.data.todayAddRemindNum
              this.list[2].data[1].value=res.data.totalCaredNum
              this.list[2].data[1].plus=res.data.todayAddCaredNum
          }
        })
      },

    //设备数量占比统计
    getDeviceCountData(){
      deviceCountData({}).then(res=>{
        if(res.code==200){
          this.list2[1].data[0].value=res.data.bindNum
          this.list2[1].data[1].value=res.data.unbindNum
        }
      })
    },
    //患者对医生的评价占比统计
      getPatientEvaluateCountData(){
        patientEvaluateCountData({}).then(res=>{
          if(res.code==200){
          this.list2[2].data=   res.data.map((item,index)=>{
             return {
                title:item.groupName,
                value:item.evaluateNum,
                color:this.colors[2-index]
              }
            })
          }
        })
      },
    //患者年龄占比统计
    getPatientAgeCountData(){
      patientAgeCountData({}).then(res=>{
        if(res.code==200){
          this.list3[1].data=res.data.map((item,index)=>{
             return {
                title:item.ageGroupName,
                value:item.num,
                color:this.colors[index]
              }
            })
          }
      })
    },
    //患者性别占比统计
    getPatientSexCountData(){
      patientSexCountData({}).then(res=>{
        if(res.code==200){
          this.list3[2].data[0].value=res.data.manNum
          this.list3[2].data[1].value=res.data.womanNum
          }
      })
    },
    //患者区域分布统计
    getPatientAreaScatterCountData(){
      patientAreaScatterCountData({cityName:'宜宾市'}).then(res=>{
        if(res.code==200){
           this.mapData=res.data
        }
      })
    },
    //测量数据
    getNewestBloodTestList() {
      newestBloodTestList(this.queryParams)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data
          }
        })
    },
      initWebSocket(){ //初始化weosocket
        const wsuri = process.env.VUE_APP_BASE_API.replace('http','ws')+"/websocket";
        // const wsuri = "ws://192.168.0.200:8081/websocket";
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        // this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
        this.$bus.$on('websocketonmessage',this.handleMessage)
      },
      websocketclose(){
        this.initWebSocket()
      },
       websocketonopen(){ //连接建立之后执行send方法发送数据
        let userId=JSON.parse(sessionStorage.getItem('user')).userId,
        roleId=sessionStorage.getItem('roleId');
        this.websocketsend(`${userId}#${roleId}#${getToken()}`);
      },
       websocketsend(Data){//数据发送
          this.websock.send(Data);
        },
      websocketonmessage(e){ //数据接收
          this.$bus.$emit('websocketonmessage',e)
      },
      handleMessage(e){
        try{
          if(e.data&&e.data!='连接成功'&&e.data!='更新统计'){
            if(e.data=='大屏-患者人数KPI'){
               this.getPatientNumKpiData()
            }else if(e.data=='大屏-患者测量行为指标KPI'){
               this.getPatientTestActionKpiData()
            }else if(e.data=='大屏-医生任务指标KPI'){
               this.getDoctorTaskKpiData()
            }else if(e.data=='大屏-患者区域分布'){
               this.getPatientAreaScatterCountData()
            }else if(e.data=='大屏-患者对医生的评价占比'){
              this.getPatientEvaluateCountData()
            }else if(e.data=='大屏-设备数量占比'){
              this.getDeviceCountData()
            }else if(e.data=='大屏-患者年龄占比'){
             this.getPatientAgeCountData()
            }else if(e.data=='大屏-患者性别占比'){
             this.getPatientSexCountData()
            }else{
              let temp=JSON.parse(e.data)
              temp.testDate= parseTime(new Date(temp.testDate))
               this.tableData.unshift(temp)
               if(this.tableData.length>9){
                 this.tableData.splice(9,1)
               }
            }

          }
        }catch(e){

        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  ::-webkit-scrollbar{
    width: 0;
  }
 .screen{
   width: 100vw;
   background: #122A48;
   height: 100vh;
   overflow-y: scroll;
   position: fixed;
   z-index: 2000;
   left: 0;
   top: 0;
   padding-top: 0.2vw;
   box-sizing: border-box;
   .pointer{
     cursor: pointer;
   }
   .full-btn{
     position: absolute;
     right:10vw;
     top:1vw;
     z-index: 1000;
     color: #fff;
     font-size: 1vw;
   }
   .content{
     .title{
       color:#fff;
       font-size: 1.9vw;
       text-align: center;
       background-image: url("~@/assets/screen/img1.png");
       background-size: cover;
       background-position: center center;
       width: 100vw;
       height: 5.78vw;
       display: flex;
       justify-content: center;
       align-items: center;
       padding-bottom: 0.5vw;
       box-sizing: border-box;
       .logo{
         width: 2.5vw;
         height: 2.5vw;
         margin-right: 10px;
       }
     }
     .role-name{
       position: absolute;
       left:10vw;
       top:1vw;
       z-index: 1000;
       color: #fff;
       font-size: 1vw;
     }

     .time{
       position: absolute;
       right:10vw;
       top:3.8vw;
       z-index: 1000;
       color: #fff;
       font-size: 1vw;
     }
     .flex{
       display: flex;
       .chart-wrap{
         width: 24vw;
         margin-left: 1vw;
       }
       .flex-center{
         width: 48vw;
         margin-left: 1vw;
       }
     }
   }
 }

</style>
